﻿using System;
using System.Collections.Specialized;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.StsAdmin;
using MSPE.Public.FOSS.AutoStatusPlus.Common;
using MSPE.Public.FOSS.AutoStatusPlus.StsAdm.OperationHelpers;
using MSPE.Public.FOSS.AutoStatusPlus.StsAdm.SPValidators;

namespace MSPE.Public.FOSS.AutoStatusPlus.StsAdm.Commands
{
    class AspSetPolling : SPOperation
    {
        #region Constructors
        /// <summary>
        /// Constructs a new instance of the <see cref="AspSetPolling" /> class.
        /// </summary>
        public AspSetPolling()
        {
            SPParamCollection _parameters = new SPParamCollection
                                               {
                                                   new SPParam(GlobalConstants.UrlParamName, GlobalConstants.UrlParamName, true, null,
                                                               new SPUrlValidator(),
                                                               "Please specify the PWA site."),
                                                   new SPParam(GlobalConstants.PollingIntervalParamName, 
                                                               GlobalConstants.PollingIntervalParamName, true,
                                                               null, new SPIntRangeValidator(0, int.MaxValue),
                                                               "Please specify a valid polling interval.")
                                               };

            StringBuilder _sb = new StringBuilder();
            _sb.Append("\r\n\r\nAspSetPolling");
            _sb.AppendLine();
            _sb.Append("\r\n\tThis command is used to adjust AutoStatusPlus' polling interval.");           
            _sb.Append("\r\n\r\nParameters:");
            _sb.Append("\r\n\t-url <PWA Site Url>");
            _sb.Append("\r\n\t-interval <Minutes between timer job executions>");
            _sb.AppendLine();
            _sb.AppendLine();
            _sb.Append("\r\nValid values for the -interval parameter are: 1 - 2147483647");

            Init(_parameters, _sb.ToString());
        } // AutoStatusPlusSetInterval()
        #endregion // Constructors

        #region Methods
        #region Overrides
        public override int Execute(string command, StringDictionary keyValues, out string output)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Gets the help message.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <returns></returns>
        public override string GetHelpMessage(string command)
        {
            return HelpMessage;
        }

        /// <summary>
        /// Runs the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="keyValues">The key values.</param>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override int Run(string command, StringDictionary keyValues, out string output)
        {
            SPSite _site = null;
            SPWeb _pwaWeb = null;

            try
            {
                #region Read configuration settings from command line
                output = string.Empty;

                InitParameters(keyValues);

                // Read params into local fields
                string _pollingInterval = Params[GlobalConstants.PollingIntervalParamName].Value;
                string _url = Params[GlobalConstants.UrlParamName].Value.TrimEnd('/');

                // This routine stores the settings in the PWA site's property bag
                _site = new SPSite(_url);

                if (_site.Url != _url)
                    throw new Exception("You may only configure Project Web Access Sites.");

                _pwaWeb = _site.RootWeb;

                if (_pwaWeb == null)
                    throw new Exception("Could not load the Site at the specified URL.");

                if (_pwaWeb.WebTemplateId != GlobalConstants.PwaSiteTemplateId)
                    throw new Exception("You may only configure Project Web Access Sites.");
                #endregion // Read configuration settings from command line

                #region Load and update configuration settings
                Settings _loadedSettings = Settings.LoadSettings(_pwaWeb);
                _loadedSettings.PollingInterval = int.Parse(_pollingInterval);
                Settings.UpdateSettings(_pwaWeb, _loadedSettings);

                // Reload settings and recreate timer job
                _loadedSettings = Settings.LoadSettings(_pwaWeb);
                int _deletedJobs = Utility.CreateTimerJob(_pwaWeb, _loadedSettings);

                output = string.Format("Deleted {0} timer job(s).\r\nCreated 1 new timer job with an interval of {1} minutes.\r\n\r\nOperation completed successfully.",
                                       _deletedJobs, _pollingInterval);
                #endregion // Load and update configuration settings

                // Use the ErrorCodes enum to return error codes: 
                // ErrorCodes.SyntaxError
                // ErrorCodes.GeneralError

                // Return 0 for success.)
                return 0;
            }
            catch (Exception ex)
            {
                throw new Exception("Error encountered while setting event:\n\n" + ex.ToString());
            }

            finally
            {
                if (_pwaWeb != null) _pwaWeb.Dispose();
                if (_site != null) _site.Dispose();
            }
        }

        #endregion // Overrides
        #endregion // Methods
    }
}
